<template>
  <div class="roles">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ name: 'Home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-form inline size="small">
      <el-form-item>
        <el-button type="primary" @click="handleAdd">添加角色</el-button>
      </el-form-item>
    </el-form>

    <!-- <input id="check" @change="handleChange" class="btn" type="checkbox" />
    <label class="two" for="check">
      <img
        src="https://th.bing.com/th/id/OIP.vDdElA5aKfI8K1JyQGPK9wHaGo?w=226&h=202&c=7&r=0&o=5&dpr=2&pid=1.7"
        alt=""
        srcset=""
      />
    </label>
    <label class="one" for="check">
      <img
        src="https://th.bing.com/th/id/OIP.aRZ4s7h_NJbBA4WTKMNnygHaHa?w=216&h=216&c=7&r=0&o=5&dpr=2&pid=1.7"
        alt=""
        srcset=""
      />
    </label> -->

    <el-table v-loading="showLoading" :data="tableData" style="width: 100%">
      <el-table-column type="expand">
        <template slot-scope="scope">
          <el-row v-for="(item, index) in scope.row.children" :key="item.id">
            <el-col :span="4">
              <el-tag
                closable
                @close="
                  deleteRightsByRole({
                    roleId: scope.row.id,
                    rightId: item.id,
                    $index: scope.$index,
                    index,
                  })
                "
                >{{ item.authName }}</el-tag
              >
              <i class="el-icon-arrow-right"></i>
            </el-col>
            <el-col :span="20">
              <el-row v-for="(_item, _index) in item.children" :key="_item.id">
                <el-col :span="4">
                  <el-tag
                    closable
                    @close="
                      deleteRightsByRole({
                        roleId: scope.row.id,
                        rightId: _item.id,
                        $index: scope.$index,
                        index,
                        _index,
                      })
                    "
                    >{{ _item.authName }}</el-tag
                  >
                  <i class="el-icon-arrow-right"></i>
                </el-col>
                <el-col :span="20">
                  <el-tag
                    closable
                    v-for="(__item, __index) in _item.children"
                    :key="__item.id"
                    @close="
                      deleteRightsByRole({
                        roleId: scope.row.id,
                        rightId: __item.id,
                        $index: scope.$index,
                        index,
                        _index,
                        __index,
                      })
                    "
                    >{{ __item.authName }}</el-tag
                  >
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column prop="roleName" label="角色名称"></el-table-column>
      <el-table-column prop="roleDesc" label="描述"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="small"
            circle
            @click="editRole(scope.row)"
          ></el-button>
          <el-popconfirm title="确定删除吗？" @confirm="delRole(scope.row.id)">
            <el-button
              type="info"
              icon="el-icon-delete"
              size="small"
              slot="reference"
              circle
            ></el-button>
          </el-popconfirm>
          <el-button
            type="info"
            icon="el-icon-edit"
            size="small"
            circle
            @click="handleRoles(scope.row)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      :visible.sync="dialogVisible"
      title="角色信息"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form :model="roleForm" ref="roleForm" :rules="roleFormRules">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="roleDesc">
          <el-input type="textarea" v-model="roleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveRole">保存</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="roleDialog" title="分配权限">
      <el-tree
        node-key="id"
        show-checkbox
        :data="rightsTree"
        :props="defaultProps"
        ref="tree"
        default-expand-all
      ></el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="roleDialog = false">取消</el-button>
        <el-button type="primary" @click="saveRight">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getRoles,
  addRole,
  deleteRole,
  updateRole,
  deleteRightsByRole,
  getRights,
  giveRoleRights,
} from "@/http/api";

export default {
  data() {
    return {
      query: "",
      tableData: [],
      total: 0,
      showLoading: false,
      dialogVisible: false,
      roleForm: {
        roleName: "",
        roleDesc: "",
      },
      roleFormRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
        roleDesc: [{ required: true, message: "请输入描述", trigger: "blur" }],
      },
      add: false,
      roleDialog: false,
      defaultProps: {
        label: "authName",
        children: "children",
      },
      rightsTree: [],
      curRigths: [],
    };
  },
  methods: {
    async getRoles() {
      this.showLoading = true;
      const res = await getRoles();
      this.tableData = res;
      this.showLoading = false;
      console.log(res);
    },
    handleAdd() {
      this.dialogVisible = true;
      this.add = true;
      this.$nextTick(() => {
        this.$refs.roleForm.clearValidate();
      });
    },
    async saveRole() {
      try {
        await this.$refs.roleForm.validate();
        if (this.add) {
          await addRole(this.roleForm);
        } else {
          await updateRole(this.roleForm);
        }
        this.dialogVisible = false;
        this.getRoles();
      } catch (error) {
        console.log("校验未通过");
      }
    },
    editRole(role) {
      this.dialogVisible = true;
      this.roleForm = { ...role };
      this.$nextTick(() => {
        this.$refs.roleForm.clearValidate();
      });
    },
    async delRole(id) {
      await deleteRole(id);
      this.getRoles();
    },
    //删除用户权限
    async deleteRightsByRole({ roleId, rightId, ...args }) {
      await deleteRightsByRole({ roleId, rightId });
      console.log(args);
      //获取对象所有的key值，返回数组
      let arr = Object.values(args);
      switch (arr.length) {
        case 2:
          this.tableData[arr[0]].children.splice(arr[1], 1);
          break;
        case 3:
          this.tableData[arr[0]].children[arr[1]].children.splice(arr[2], 1);
          break;
        default:
          this.tableData[arr[0]].children[arr[1]].children[
            arr[2]
          ].children.splice(arr[3], 1);
          break;
      }
      // this.getRoles();
    },
    // handleChange(e) {
    //   console.log(e.target.checked);
    // },
    //处理获取选中的nodes
    handleRights(arr) {
      let arrs = [];
      arr.map((item) => {
        item.children.map((_item) => {
          _item.children.map((__item) => {
            arrs.push(__item.id);
          });
        });
      });
      return arrs;
    },
    //显示分配权限弹窗
    handleRoles(row) {
      this.roleForm = row;
      this.roleDialog = true;
      const _rights = this.handleRights(row.children);
      this.$nextTick(() => {
        this.$refs.tree.setCheckedKeys(_rights);
      });
    },
    //分配权限
    async saveRight() {
      const rid = [
        ...this.$refs.tree.getCheckedKeys(),
        ...this.$refs.tree.getHalfCheckedKeys(),
      ];
      try {
        await giveRoleRights({ id: this.roleForm.id, rids: rid.join(",") });
        this.getRoles();
        this.roleDialog = false;
      } catch (error) {
        console.log(error);
        return error;
      }
    },
    //获取所有权限列表tree
    async getRights() {
      const res = await getRights();
      this.rightsTree = res;
      console.log(res);
    },
  },
  created() {
    this.getRoles();
    this.getRights();
  },
};
</script>

<style>
.btn {
  all: unset;
}
.btn ~ .two {
  display: inline-block;
}
.btn ~ .one {
  display: none;
}
.btn:checked ~ .one {
  display: inline-block;
}
.btn:checked ~ .two {
  display: none;
}
</style>
